package co.salehi.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import co.salehi.domain.Battery;
import co.salehi.domain.Cart;

@RooWebScaffold(path = "batterys", formBackingObject = Battery.class)
@RequestMapping("/batterys")
@Controller
public class BatteryController {

	@RequestMapping(params = { "addToCart", "selectedItems" }, method = RequestMethod.GET)
	public String addToCart(Model uiModel, HttpServletRequest request) {

		String str = request.getParameter("selectedItems");

		Cart sessionCart = request.getSession().getAttribute("cart") == null ? new Cart()
				: (Cart) request.getSession().getAttribute("cart");

		for (String idStr : str.split(",")) {
			sessionCart.getBatteryIds().add(Long.parseLong(idStr));
		}

		request.getSession().setAttribute("cart", sessionCart);

		return "batterys/list";
	}
	
    @RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") Long id, Model uiModel) {
        uiModel.addAttribute("battery", Battery.findBattery(id));
        addDateTimeFormatPatterns(uiModel);
        return "batterys/update";
    }
    
	@PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        Battery.findBattery(id).remove();
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/batterys";
    }

	@PreAuthorize("hasAuthority('ROLE_ADMIN')")
	@RequestMapping(method = RequestMethod.GET, params = { "soldouts" })
	public String listSolds(
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "size", required = false) Integer size,
			Model uiModel) {
		if (page != null || size != null) {
			int sizeNo = size == null ? 10 : size.intValue();
			uiModel.addAttribute("batterys", Battery.findSoldBatteryEntries(
					page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));
			float nrOfPages = (float) Battery.countSoldBatteries() / sizeNo;
			uiModel.addAttribute(
					"maxPages",
					(int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1
							: nrOfPages));
		} else {
			uiModel.addAttribute("batterys", Battery.findAllSoldBatteries());
		}
		addDateTimeFormatPatterns(uiModel);
		return "batterys/listSolds";
	}

	@PreAuthorize("hasAuthority('ROLE_ADMIN')")
	@RequestMapping(params = { "unsell", "selectedItems" }, method = RequestMethod.GET)
	public String unsell(Model uiModel, HttpServletRequest request) {

		String str = request.getParameter("selectedItems");

		for (String idStr : str.split(",")) {
			Battery battery = Battery.findBattery(Long.parseLong(idStr));
			battery.setSellDate(null);
			battery.merge();
		}

		uiModel.addAttribute("soldouts", true);
		return "batterys/listSolds";
	}


}
